# 前端和硬件之间的逻辑控制层（便于更换硬件）
import json
import os
import time

from PyQt6.QtCore import pyqtSignal,QObject
import pandas as pd
from datetime import datetime
from src.device.motor_SM150 import motor_SM150
from src.device.spectormeter_seabreeze import SpectrometerController

class Control(QObject):
	signal_finish_indexdata = pyqtSignal(int)  # 自定义信号
	#载物平台孔位数量int，端口名str
	def __init__(self):
		super().__init__()
		self.motor_conn = False
		self.spec_conn = False
		self.motor = None
		self.spectrometer = None
		self.num_platform = 16
		self.offset_angel = 8
		self.background_x = [0] * 2500
		self.background_y = [0] * 2500
		self._background_input()



	#
	def motor_connect(self, DEVICENAME):
		self.motor = motor_SM150(DEVICENAME)  # 传入端口号,如果之后更换了电机，可直接实例化其他电机
		if self.motor.motor_connect():
			self.motor_conn = True
			return True
		else:
			self.motor_conn = False
			return False

	def motor_disconncect(self):
		self.motor.motor_disconncet()

	#从0号孔位开始,如num_platform==9，那么index就是0-8
	def move_motor_to_index(self,index :int):
		angle = (360/self.num_platform)*index + self.offset_angel
		self.motor.move_motor_to_angle(angle)

	#光谱仪按下连接按钮后执行
	def spectormeter_connect(self):
		print("实例化光谱仪连接")
		self.spectrometer = SpectrometerController()
		if self.spectrometer.print_modle():
			self.spec_conn = True
			return True
		else:
			self.spec_conn = False
			return False

	#初始化背景光谱
	def _background_input(self):
		if os.path.exists('data/background/background.csv'):
			print("背景文件存在，开始读入背景")
			#读取csv的第一列数据,并变为list类型
			self.background_x:list = pd.read_csv('data/background/background.csv', usecols=[0]).values.flatten().tolist()
			#读取csv的第二列数据
			self.background_y:list = pd.read_csv('data/background/background.csv', usecols=[1]).values.flatten().tolist()
		else:
			print("背景文件不存在")
			self.background_x = [0] * 2500
			self.background_y = [0] * 2500

	#获取背景光谱
	def get_save_background(self,integration_time, average_times):
		print("开始获取背景光谱")
		try:
			self.spectrometer.start_and_set(0, integration_time, average_times)
			self.spectrometer.close_laser_switch()
			time.sleep(0.2)
			listx, listy = self.spectrometer.run_sp()
			self.background_x = listx
			self.background_y = listy
			df = pd.DataFrame({'listx': listx, 'listy': listy})
			# 检查文件夹路径是否存在，如果不存在则创建
			if not os.path.exists(r'data/background/'):
				os.makedirs(r'data/background/')
			# 拼接文件路径
			file_path = os.path.join(r'data/background/', 'background.csv')
			# 将DataFrame保存为CSV文件
			df.to_csv(file_path, index=False, header=False)
			return listx, listy
		except:
			print("光谱仪连接失败，检查连接")


	#删除背景光谱
	def delete_background(self):
		if os.path.exists('data/background/background.csv'):
			os.remove('data/background/background.csv')
			self.background_x = [0]*2500
			self.background_y = [0]*2500
		else:
			print("背景文件不存在")

	#检测逻辑，传入检测的孔位list
	#2024.1.11，暂时只有电机运动逻辑
	def run(self,check_index :list, power, integration_time, average_times, project_name):

		#开启光谱仪和设置
		print("开始打开光谱仪激光器")
		self.spectrometer.start_and_set(power, integration_time, average_times)
		for index in check_index:
			print(f"当前执行第{index}孔位操作")
			self.move_motor_to_index(index=index)#位移至孔位位置,还未测试
			#执行检测，光谱仪返回两个数组
			listx,listy = self.spectrometer.run_sp()
			#listy减去背景
			remove_y = [listy[i] - self.background_y[i] for i in range(min(len(listy), len(self.background_y)))]

			#把这个index作为命名放入temp文件夹里
			# 将数据保存到JSON文件
			data = {"index": index, "listx": listx, "listy": remove_y}
			json_data = json.dumps(data)
			# 创建temp文件夹（如果不存在）
			temp_folder = "./data/temp"
			os.makedirs(temp_folder, exist_ok=True)
			# 创建项目文件夹(如果不存在)
			project_folder = f"./data/csv/{project_name}"
			os.makedirs(project_folder, exist_ok=True)
			# 构建文件名并保存JSON文件
			filename = os.path.join(temp_folder, f"data_{index}.json")
			with open(filename, "w") as json_file:
				json_file.write(json_data)
			# 保存csv进项目文件夹
			current_time = datetime.now()
			formatted_time = current_time.strftime("%Y_%m_%d_%H_%M_%S_%f")
			csv_filename = f"{project_name}_{formatted_time}.csv"
			df = pd.DataFrame({'listx': listx, 'listy': remove_y})
			df.to_csv(project_folder+"/"+csv_filename, index=False, header=False)
			# 发送信号通知用户 该index数据收集完成
			self.signal_finish_indexdata.emit(index)
		# 关闭激光和光谱仪
		self.spectrometer.cease_spec()

	def print_test_slot(self,index):
		print(index)

if __name__ == "__main__":
	control_inst = Control()
	control_inst.motor_connect("COM4")
	control_inst.run([1,15],1,1,1)














